<?php
/**
 * Save.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/06/07
 * Time: 14:04
 */
namespace app\api\open\user;

use app\api\model\SimpleRbacUser;
use app\api\open\Base;
use think\Db;
use think\Validate;

class Save extends Base
{
    protected $user_id = null;
    protected $userData = [];
    /**
     * Save constructor.
     * @throws \Exception
     */
    public function __construct($param=[])
    {
        $this->prevent();

        parent::__construct($param);

        $param = $this->params;

        // 验证请求参数
        $validate = new Validate([
            // step1
            "username" => "require",
            "password" => "require",
            "phone" => "require",
            "email" => "require",
            "nick_name" => "require",
            "real_name" => "require",
            "remark" => "require",
            "sex" => "require",
            "roles" => "require"
        ]);
        $check = $validate->check($param);
        if($check === false){
            // 验证失败 输出错误信息
            throw new \Exception($validate->getError(),1);
        }
        if(!empty($param['id']))
        {
            $this->user_id = $param['id'];
        }
        // 用户名
        $this->userData['username'] = $param['username'];
        // 电话
        $this->userData['phone'] = $param['phone'];
        // 密码提示
//        $this->userData['pawrd'] = $param['pawrd'];
        // 加密密码
        $this->userData['password'] = md5($param['password']);
        // 昵称
        $this->userData['nick_name'] = $param['nick_name'];
        // 真实姓名
        $this->userData['real_name'] = $param['real_name'];
        // 邮箱
        $this->userData['email'] = $param['email'];
        // 用户简介
        $this->userData['remark'] = $param['remark'];
        // 角色(,1,2,3,)
        $deCodeRoles = json_decode($param['roles'],true);
        if(empty($deCodeRoles))
        {
            $this->userData['roles'] = '';
        }else{
            $this->userData['roles'] = ','.implode(",",$deCodeRoles).',';
        }
        // 锁定(0:否,1:是)
        $this->userData['lock'] = empty($param['lock'])?0:1;
        // 头像
        // $this->userData['avatar'] = mt_rand(1,255);
        // 头像
        $this->userData['sex'] = empty($param['sex'])?0:$param['sex'];
        // 平台ID
        $this->userData['platform_id'] = config('platform_info.id');

    }

    public function index($param=[])
    {
        Db::startTrans();
        try
        {
            // 保存商品主表信息
            $user_id = SimpleRbacUser::getInstance()->save($this->user_id,$this->userData);
            if(!$user_id)
            {
                throw new \Exception("保存用户信息失败",2);
            }
        }
        catch (\Exception $e)
        {
            // 出现错误进行回滚处理
            Db::rollback();
            // 统一错误抛出
            throw new \Exception("保存失败：".$e->getMessage(),$e->getCode());
        }

        Db::commit();
        return ['id'=>empty($this->user_id)?$user_id:$this->user_id];
    }
}